package cn.achao.csr.mybatis.config;

import cn.achao.csr.api.SequenceApi;
import cn.achao.csr.base.constant.SecurityConstants;
import cn.achao.csr.base.entity.BaseEntity;
import cn.achao.csr.base.utils.SnowflakeIdUtils;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 实现mybatis id生成接口,使用美团号段模式
 * @Author: achao
 **/

@Slf4j
@Component
@RequiredArgsConstructor
public class IdGeneratorConfig implements IdentifierGenerator {

    private final SequenceApi sequenceApi;

    @Override
    public Number nextId(Object entity) {
        log.info("mybatis id生成器开始执行...");
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            String key = baseEntity.sequenceCode();
            Long id = baseEntity.getId();
            if (id != null) {
                return id;
            }
            id = sequenceApi.getSegmentId(key, SecurityConstants.INNER);
            if (id.toString().length() > 18) {
                log.warn("序列key【{}】 请检查序列服务是否宕机...", key);
            }
            return id;
        }
        return null;
    }


}
